<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #f5f5f5;
        }

        .login-container {
            width: 400px;
            background: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .close-button {
            float: right;
            font-size: 20px;
            color: #999;
            cursor: pointer;
            border: none;
            background: none;
            padding: 5px;
        }

        .tab-switch {
            display: flex;
            margin-bottom: 30px;
            border-bottom: 1px solid #eee;
        }

        .tab-switch button {
            flex: 1;
            padding: 15px;
            border: none;
            background: none;
            font-size: 16px;
            color: #666;
            cursor: pointer;
            position: relative;
        }

        .tab-switch button.active {
            color: #00a7ff;
        }

        .tab-switch button.active::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            width: 100%;
            height: 2px;
            background: #00a7ff;
        }

        .input-group {
            margin-bottom: 20px;
            position: relative;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            color: #666;
        }

        .input-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .input-group .code-button {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            padding: 6px 12px;
            background: #00a7ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .submit-button {
            width: 100%;
            padding: 12px;
            background: #00a7ff;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 20px;
        }

        .submit-button:hover {
            background: #0095ee;
        }

        .phone-prefix {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
        }

        .phone-input {
            padding-left: 50px !important;
        }

        .forgot-password {
            float: right;
            color: #00a7ff;
            text-decoration: none;
            font-size: 14px;
        }

        .register-link {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #666;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 15px;
        }

        .register-link a {
            color: #00a7ff;
            text-decoration: none;
            padding: 8px 20px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .register-link a:hover {
            background-color: rgba(0, 167, 255, 0.1);
        }

        .register-link .divider {
            width: 30px;
            height: 1px;
            background: #ddd;
            margin: 5px 0;
        }

        .loading-spinner {
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #00a7ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 10px auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .code-button:disabled {
            background-color: #ccc !important;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <button class="close-button">×</button>
        <div class="tab-switch">
            <button class="active" onclick="switchTab('password')">密码登录</button>
            <button onclick="switchTab('sms')">短信登录</button>
            <button onclick="switchTab('wechat')">扫码登录</button>
        </div>

        <!-- 密码登录表单 -->
        <div id="password-login">
            <div class="input-group">
                <input type="text" placeholder="请输入账号" />
            </div>
            <div class="input-group">
                <input type="password" placeholder="请输入密码" />
            </div>
            <button class="submit-button" onclick="passwordLogin()">登录</button>
        </div>

        <!-- 短信登录表单 -->
        <div id="sms-login" style="display: none;">
            <div class="input-group">
                <span class="phone-prefix">+86</span>
                <input type="text" class="phone-input" placeholder="请输入手机号" />
            </div>
            <div class="input-group">
                <input type="text" placeholder="请输入验证码" />
                <button class="code-button" onclick="sendSmsCode()">获取验证码</button>
            </div>
            <button class="submit-button" onclick="smsLogin()">登录/注册</button>
        </div>

        <!-- 添加微信扫码登录的界面 -->
        <div id="wechat-login" style="display: none;">
            <div class="qrcode-container" style="text-align: center; padding: 20px;">
                <div id="qrcode-wrapper" style="margin-bottom: 15px;">
                    <img id="qrcode-img" style="width: 200px; height: 200px;" />
                </div>
                <p id="scan-tip" style="color: #666;">请使用微信扫描二维码登录</p>
                <div class="loading-wrapper" style="display: none;">
                    <div class="loading-spinner"></div>
                    <p>扫描成功，请在微信中确认</p>
                </div>
            </div>
        </div>

        <div class="register-link">
            <a href="register.html">
                <span style="margin-right: 5px;">还没有账号？</span>
                <span style="color: #00a7ff;">立即注册</span>
            </a>
            <div class="divider"></div>
            <a href="forget-password.html">忘记密码？</a>
        </div>
    </div>

    <script>
        let smsCountdown = 0;
        let countdownTimer = null;

        // 发送验证码
        function sendSmsCode() {
            const phone = document.querySelector('#sms-login .phone-input').value.trim();
            const codeButton = document.querySelector('#sms-login .code-button');
            
            console.log('发送验证码 - 手机号:', phone); // 添加日志
            
            if (smsCountdown > 0) return;
            
            if (!phone) {
                alert('请输入手机号');
                return;
            }
            
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                alert('请输入正确的手机号');
                return;
            }

            fetch('sendCode', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `phone=${phone}&type=login`
            }).then(response => response.json())
              .then(data => {
                  console.log('发送验证码响应:', data); // 添加日志
                  if (data.success) {
                      smsCountdown = 60;
                      codeButton.disabled = true;
                      
                      countdownTimer = setInterval(() => {
                          smsCountdown--;
                          codeButton.innerText = `重新发送(${smsCountdown}s)`;
                          
                          if (smsCountdown <= 0) {
                              clearInterval(countdownTimer);
                              codeButton.disabled = false;
                              codeButton.innerText = '获取验证码';
                          }
                      }, 1000);
                      
                      alert("验证码已发送！");
                  } else {
                      alert(data.message || "验证码发送失败！");
                  }
              }).catch(error => {
                  console.error('发送验证码错误:', error);
                  alert('发送验证码失败，请重试');
              });
        }

        // 密码登录
        function passwordLogin() {
            const username = document.querySelector('#password-login input[type="text"]').value;
            const password = document.querySelector('#password-login input[type="password"]').value;
            
            if (!username || !password) {
                alert('请输入账号和密码');
                return;
            }

            fetch('login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `type=username&username=${username}&password=${password}`
            }).then(response => response.json())
              .then(data => {
                  if (data.success) {
                      window.location.href = 'game-home.html';
                  } else {
                      alert(data.message || '登录失败');
                  }
              });
        }

        // 短信登录
        function smsLogin() {
            const phone = document.querySelector('#sms-login .phone-input').value.trim();
            const code = document.querySelector('#sms-login input[placeholder="请输入验证码"]').value.trim();
            
            console.log('登录信息 - 手机号:', phone, '验证码:', code); // 添加日志
            
            if (!phone || !code) {
                alert('请输���手机号和验证码');
                return;
            }

            if (!/^1[3-9]\d{9}$/.test(phone)) {
                alert('请输入正确的手机号');
                return;
            }

            fetch('login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `type=phone&phone=${phone}&code=${code}`
            }).then(response => response.json())
              .then(data => {
                  console.log('登录响应:', data); // 添加日志
                  if (data.success) {
                      if (data.needSetPassword) {
                          window.location.href = 'set-password.html';
                      } else {
                          window.location.href = 'game-home.html';
                      }
                  } else {
                      alert(data.message || '登录失败');
                  }
              }).catch(error => {
                  console.error('登录错误:', error);
                  alert('登录请求失败，请重试');
              });
        }

        function switchTab(type) {
            const buttons = document.querySelectorAll('.tab-switch button');
            buttons.forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');

            document.getElementById('password-login').style.display = type === 'password' ? 'block' : 'none';
            document.getElementById('sms-login').style.display = type === 'sms' ? 'block' : 'none';
            document.getElementById('wechat-login').style.display = type === 'wechat' ? 'block' : 'none';

            if (type === 'wechat') {
                getWeChatQrCode();
            }
        }

        // 添加关闭按钮功能
        document.querySelector('.close-button').addEventListener('click', () => {
            window.close();
        });

        // 获取微信登录二维码
        function getWeChatQrCode() {
            const qrcodeContainer = document.getElementById('qrcode-wrapper');
            const scanTip = document.getElementById('scan-tip');
            const loadingWrapper = document.querySelector('.loading-wrapper');
            
            fetch('wechatLogin?action=getQrCode')
                .then(response => response.json())
                .then(data => {
                    if (data.ticket) {
                        document.getElementById('qrcode-img').src = 
                            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + data.ticket;
                        startCheckLogin(data.sceneStr);
                    } else {
                        scanTip.textContent = '获取二维码失败，请刷新重试';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    scanTip.textContent = '获取二维码失败，请刷新重试';
                });
        }

        // 检查登录状态
        function startCheckLogin(sceneStr) {
            const scanTip = document.getElementById('scan-tip');
            const loadingWrapper = document.querySelector('.loading-wrapper');
            let checkCount = 0;
            const maxChecks = 60; // 最多检查60次（2分钟）

            const checkInterval = setInterval(() => {
                if (checkCount >= maxChecks) {
                    clearInterval(checkInterval);
                    scanTip.textContent = '二维码已过期，请刷新重试';
                    scanTip.style.display = 'block';
                    loadingWrapper.style.display = 'none';
                    return;
                }

                fetch('wechatLogin?action=checkLogin&sceneStr=' + sceneStr)
                    .then(response => response.json())
                    .then(data => {
                        if (data.scanned && !data.success) {
                            // 已扫码但未确认
                            scanTip.style.display = 'none';
                            loadingWrapper.style.display = 'block';
                        } else if (data.success) {
                            // 登录成功
                            clearInterval(checkInterval);
                            loadingWrapper.querySelector('p').textContent = '登录成功，正在跳转...';
                            setTimeout(() => {
                                // 根据返回的redirectUrl进行跳转
                                window.location.href = data.redirectUrl;
                            }, 1000);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });

                checkCount++;
            }, 2000); // 每2秒检查一次
        }
    </script>
</body>
</html> 